/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrder = function(root) {
  if(root === null) return []
  const queue = []
  queue.push(root)
  let pos = 0, levelPos = 1,rear = 1
  let ans = []
  let temp = []
  while(queue.length > 0) {
    let tempNode = queue.unshift()
    temp.push(tempNode)
    pos++
    if(tempNode.left) {
      queue.push(tempNode.left)
      rear++
    }
    if(tempNode.right) {
      queue.push(tempNode.right)
      rear++
    }
    if(pos == levelPos) {
      ans.push(temp)
      temp = []
      levelPos = rear
    }
  }
  return ans
};
// 更优解
var levelOrder = function(root) {
  if (root === null) return [];
  let ans = [];
  let cur = [root];
  while (cur.length) {
      let nxt = [];
      let vals = [];
      for (const node of cur) {
          vals.push(node.val);
          if (node.left)  nxt.push(node.left);
          if (node.right) nxt.push(node.right);
      }
      cur = nxt;
      ans.push(vals);
  }
  return ans;
};
var levelOrder3 = function(root) {
  if(root === null) return []
  let ans = []
  let queue = [root]
  while(queue.length > 0) {
    let temp = []
    let len = queue.length
    for(let i = 0; i < len; i++) {
      let node = queue.shift()
      temp.push(node)
      node.left && queue.push(node.left)
      node.right && queue.push(node.right)
    }
    ans.push(temp)
  }
  return ans
}